import {computeNormals, f4} from "./primitiveUtils";
import {VertexData} from "../core/vertexData";


// @ts-ignore
export function plane(width: number,
                      height: number,
                      segments_width: number = 1,
                      segments_height: number = 1): VertexData {

    let data: {
        positions: number[],
        normals: number[],
        texCoords: number[],
        indices: number[]
    } = {
        positions: [],
        normals: [],
        texCoords: [],
        indices: []
    };

    let width_half = width / 2,
        height_half = height / 2,
        gridX = segments_width,
        gridY = segments_height,
        gridX1 = gridX + 1,
        gridY1 = gridY + 1,
        segment_width = width / gridX,
        segment_height = height / gridY;


    for (let iy = 0; iy < gridY1; iy++) {
        for (let ix = 0; ix < gridX1; ix++) {
            let x = ix * segment_width - width_half;
            let y = iy * segment_height - height_half;
            data.positions.push(x,-y,0);
        }
    }

    for (let iy = 0; iy < gridY; iy++) {
        for (let ix = 0; ix < gridX; ix++) {
            let a = ix + gridX1 * iy;
            let b = ix + gridX1 * (iy + 1);
            let c = (ix + 1) + gridX1 * (iy + 1);
            let d = (ix + 1) + gridX1 * iy;

            data.indices.push(...f4(a,b,c,d));

            data.texCoords.push(
                ix / gridX, iy / gridY,
                ix / gridX, (iy + 1) / gridY,
                (ix + 1) / gridX, (iy + 1) / gridY,
                (ix + 1) / gridX, iy / gridY
            );
        }
    }

    computeNormals(data);

    return new VertexData(data);
}
